﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NUnit.Framework;

using ERPStore.Extensions;
using ERPStore.Tests;

using Microsoft.Practices.Unity;

namespace ERPStore.Coupons.Tests.Controllers
{
	[TestFixture]
	public class IncentiveApiControllerTests : TestBase
	{
		[SetUp]
		public void Setup()
		{
			base.Initialize();

			var container = GlobalConfiguration.Configuration.DependencyResolver.GetContainer();
			IncentiveService = container.Resolve<ERPStore.Services.IIncentiveService>();
			AdminIncentiveService = container.Resolve<ERPStore.Coupons.Services.AdminIncentiveService>();
		}

		protected ERPStore.Services.IIncentiveService IncentiveService { get; private set; }
		protected ERPStore.Coupons.Services.AdminIncentiveService AdminIncentiveService { get; private set; }

		[Test]
		public void Create_Coupon()
		{
			var incentiveApiController = CreateApiController<Coupons.Controllers.IncentiveApiController>();

			var model = incentiveApiController.CreateCoupon();

			Assert.IsNotNull(model);
		}

		[Test]
		public void Apply_Global_Discount_With_Coupon()
		{
			var coupon = AdminIncentiveService.CreateCoupon();

			coupon.Code = "TEST";
			coupon.ProviderName = "globaldiscount";
			coupon.DiscountPercent = 0.2d;
			coupon.Description = "Remise globale de test";
			var expirationDate = DateTime.Now.AddDays(10);
			coupon.ExpirationDate = expirationDate;

			AdminIncentiveService.SaveCoupon(coupon);

			coupon = AdminIncentiveService.GetCouponByCode("TEST");

			Assert.IsNotNull(coupon);

			var cartController = CreateController<ERPStore.Web.Cart.Controllers.CartController>();

			cartController.AddCartItem("xbox360");

			var indexView = cartController.Index() as System.Web.Mvc.ViewResult;
			var cart = indexView.Model as ERPStore.Models.OrderCart;

			var total = cart.GrandTotal;

			var u = cartController.User as ERPStore.Models.UserPrincipal;
			IncentiveService.AddCoupon(cart, coupon.Code, u);

			indexView = cartController.Index() as System.Web.Mvc.ViewResult;
			cart = indexView.Model as ERPStore.Models.OrderCart;

			Assert.AreEqual(cart.GrandTotal, total - (total * Convert.ToDecimal(coupon.DiscountPercent)));
		}

	}
}
